#include "datafile.h"
#include <QTextStream>

DataFile::DataFile() :
	document(new QDomDocument)
{
}

void DataFile::writeList(WordList *list, QString fileName) {
	QFile file(fileName);
	if (file.open(QIODevice::WriteOnly | QIODevice::Truncate))
	  file.close();
	file.open(QFile::ReadWrite | QFile::Text);
	document->setContent(&file, true);
	QDomElement root = document->createElement("wlvdata");
	root.setAttribute("version", "1.0");
	document->appendChild(root);
	QDomElement word;
	for(int i = 0; i < list->size(); i++) {
		word = document->createElement("word");
		WordItem *item = list->at(i);
		word.setAttribute("text", item->word());
		word.setAttribute("translate", item->translate());
		word.setAttribute("transcription", item->transcription());
		word.setAttribute("pluses", item->plusesCount());
		word.setAttribute("minuses", item->minusesCount());
		word.setAttribute("known", item->isKnow());
		root.appendChild(word);
	}
	QTextStream out(&file);
	document->save(out, 4);
	file.close();
}
void DataFile::readList(WordList *list, QString fileName) {
	QFile file(fileName);
	file.open(QFile::ReadOnly | QFile::Text);
	document->setContent(&file, true);
	QDomElement root = document->documentElement();
	if (root.tagName() != "wlvdata" || root.attribute("version") != "1.0")
		return;
	QDomElement child = root.firstChildElement("word");
	while (!child.isNull()) {
		list->append(new WordItem(child.attribute("text"), child.attribute("translate"),
										child.attribute("transcription"), child.attribute("pluses").toUInt(),
										child.attribute("minuses").toUInt(), child.attribute("known").toUInt()));
		child = child.nextSiblingElement("word");
	}
	file.close();
}

void DataFile::merge(WordList *currentList, WordList *list)
{
	for(int i = 0; i < list->size(); i++)
		currentList->append(list->at(i));
	list->clear();
}

void DataFile::writeToTable(WordList *list, QTableWidget *table)
{
	   table->setRowCount(list->size());
	   for(int i = 0; i < list->size(); i++) {
		   WordItem *item = list->at(i);
		   table->setItem(i, 0, new QTableWidgetItem(item->toString()));
		   table->item(i, 0)->setData(1, i);
		   if(item->isKnow())
			   table->item(i, 0)->setBackgroundColor("green");
	   }
}
